/* Copyright 2007 Gearbox Software - http://www.gearboxsoft.com
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 
     http:www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.*/
namespace GearBlog.Web.Controllers
{
	using System.Configuration;
	using System.IO;
	using Castle.ActiveRecord;
	using GearBlog.Web.ConfigSections;
	using GearBlog.Web.Models;
	using NHibernate.Expression;

	public class SetupController : ExtendedControllerBase
	{
		private InitApp _initApp;

		public SetupController()
		{
			_initApp = (InitApp)ConfigurationManager.GetSection("InitApp");			
		}
		public void Init()
		{
			ActiveRecordStarter.CreateSchema();
			WriteHtmlMessage("Schema created.");
			CancelView();
		}
		public void ReInit()
		{
			ActiveRecordStarter.DropSchema();
			ActiveRecordStarter.CreateSchema();
            WriteHtmlMessage("Schema recreated");
			CancelView();
		}
        public void Run()
        {
            CancelView();
            if (_initApp.IsRunInit)
            {
                Init();
                InitRoles();
				CreateAdminUser();
            	CreateSetting();
                WriteHtmlMessage("Application Initialized");
            }
            else
                WriteHtmlMessage("Initialization Not Allowed.");
            
        }

		public void ShowCreateScript()
		{
			if (_initApp.IsRunInit)
			{
				string webTempFolder = string.Format(@"{0}\tmp", Context.Server.MapPath(Context.ApplicationPath));
				string scriptFile = string.Format(@"{0}\createschema.sql", webTempFolder);
				if (!Directory.Exists(webTempFolder))
					Directory.CreateDirectory(webTempFolder);
				if (File.Exists(scriptFile))
					File.Delete(scriptFile);

				ActiveRecordStarter.GenerateCreationScripts(scriptFile);
				StreamReader reader = new StreamReader(File.OpenRead(scriptFile));
				PropertyBag["createscript"] = reader.ReadToEnd();
				reader.Close();
				reader.Dispose();
			}
			else 
				WriteHtmlMessage("Initialization Not Allowed.");
		}

		private void CreateSetting()
		{
			Setting setting=new Setting();
			setting.NumOfDaysBeforeArchive = 30;
			setting.RegisteredUserOnly = false;
			setting.RegisteredUserCommentOnly = false;
			setting.Title = "Your Blog Title Here";
			setting.Description = "Your Blog Description Here";
			setting.OwnerEmail = _initApp.AdminEmail;
			setting.AllowPublicRegistration = true;
			setting.TrackBackTimeOut = 30;
			setting.ModerateComments = false;
			setting.SubmitTrackBack = true;
			setting.ReceiveTrackBack = true;
			setting.Save();
		}

		private void CreateAdminUser()
		{
			User user = User.FindFirst(new EqExpression("UserName", _initApp.AdminUserName));
			if (user == null)
			{
				user = new User();
				user.UserName = _initApp.AdminUserName;
				user.FullName = "System Administrator";
				user.Email = _initApp.AdminEmail;
			}
			// reset password, make sure user is enabled
			user.Password = _initApp.AdminPassword;
			user.ConfirmPassword = _initApp.AdminPassword;
			user.SetPasswordHash();
			user.IsEnabled = true;
			user.Roles.Add(Role.FindByName("Admins"));
			user.Save();
                
		}
        private void InitRoles()
        {
            CreateRoleIfNotExist("Admins");
            CreateRoleIfNotExist("Posters");
            WriteHtmlMessage("Roles created.");
        }
        private void CreateRoleIfNotExist(string roleName)
        {
            Role role = Role.FindOne(new EqExpression("Name", roleName));
            if (role == null)
            {
                role = new Role();
                role.Name = roleName;
                role.Save();
            }
            
            
        }
        private void WriteHtmlMessage(string message)
        {
            RenderText(string.Format("{0} <BR/>", message));
        }



	}
}
